import { useState, useEffect } from 'react';
import { useGameStore } from '@/store/game-store';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { QuestCard } from '@/components/quest-card';
import { Quest } from '@/types/game';
import { db } from '@/lib/database';
import { 
  ScrollText, 
  Star, 
  Clock, 
  CheckCircle,
  Trophy,
  Target,
  Gift
} from 'lucide-react';

export function QuestPage() {
  const { 
    player, 
    quests, 
    acceptQuest, 
    completeQuest, 
    gainExperience, 
    addGold,
    addItem 
  } = useGameStore();
  
  const [availableQuests, setAvailableQuests] = useState<Quest[]>([]);
  const [selectedTab, setSelectedTab] = useState('available');

  // 加载可用任务
  useEffect(() => {
    loadAvailableQuests();
  }, [player.level, player.realm.level]);

  const loadAvailableQuests = async () => {
    // 模拟一些任务数据
    const mockQuests: Quest[] = [
      {
        id: 'main-001',
        title: '初入修仙路',
        description: '完成第一次修炼，感受天地灵气的流动。这是每个修仙者必经的第一步，通过修炼来熟悉自己的身体和灵力。',
        type: 'main',
        status: 'available',
        requirements: {
          level: 1
        },
        rewards: {
          experience: 100,
          gold: 50,
          items: [{ id: 'health-potion', quantity: 2 }]
        },
        progress: 0,
        maxProgress: 1
      },
      {
        id: 'side-001',
        title: '收集灵草',
        description: '在附近的山林中收集10株灵草，这些灵草是炼制丹药的基础材料。小心不要被野兽发现！',
        type: 'side',
        status: 'available',
        requirements: {
          level: 1
        },
        rewards: {
          experience: 75,
          gold: 30,
          items: [{ id: 'health-potion', quantity: 1 }]
        },
        progress: 0,
        maxProgress: 10
      },
      {
        id: 'daily-001',
        title: '每日修炼',
        description: '坚持每日修炼是修仙者的基本功课。完成3次修炼来保持修为的稳定增长。',
        type: 'daily',
        status: 'available',
        requirements: {
          level: 1
        },
        rewards: {
          experience: 50,
          gold: 20
        },
        progress: 0,
        maxProgress: 3
      },
      {
        id: 'main-002',
        title: '首次战斗',
        description: '修仙路上充满危险，学会战斗是生存的必要技能。击败一只野兽来证明你的实力。',
        type: 'main',
        status: 'available',
        requirements: {
          level: 2
        },
        rewards: {
          experience: 150,
          gold: 80,
          items: [{ id: 'wooden-sword', quantity: 1 }]
        },
        progress: 0,
        maxProgress: 1
      },
      {
        id: 'side-002',
        title: '境界突破',
        description: '当修为达到一定程度时，需要尝试突破到更高的境界。成功突破到筑基期。',
        type: 'side',
        status: 'available',
        requirements: {
          level: 3,
          realm: 1
        },
        rewards: {
          experience: 200,
          gold: 100,
          items: [{ id: 'cloth-robe', quantity: 1 }]
        },
        progress: 0,
        maxProgress: 1
      }
    ];

    // 根据玩家等级和境界筛选可用任务
    const filtered = mockQuests.filter(quest => {
      const levelOk = !quest.requirements.level || player.level >= quest.requirements.level;
      const realmOk = !quest.requirements.realm || player.realm.level >= quest.requirements.realm;
      const notAccepted = !quests.some(q => q.id === quest.id);
      
      return levelOk && realmOk && notAccepted;
    });

    setAvailableQuests(filtered);
  };

  // 接受任务
  const handleAcceptQuest = (quest: Quest) => {
    acceptQuest(quest);
    setAvailableQuests(prev => prev.filter(q => q.id !== quest.id));
  };

  // 完成任务
  const handleCompleteQuest = async (quest: Quest) => {
    // 发放奖励
    gainExperience(quest.rewards.experience);
    addGold(quest.rewards.gold);
    
    // 发放物品奖励
    if (quest.rewards.items) {
      for (const itemReward of quest.rewards.items) {
        const item = await db.items.get(itemReward.id);
        if (item) {
          addItem(item, itemReward.quantity);
        }
      }
    }
    
    // 标记任务完成
    completeQuest(quest.id);
  };

  // 按状态筛选任务
  const getQuestsByStatus = (status: Quest['status']) => {
    return quests.filter(q => q.status === status);
  };

  // 按类型筛选任务
  const getQuestsByType = (type: Quest['type']) => {
    return quests.filter(q => q.type === type);
  };

  const activeQuests = getQuestsByStatus('active');
  const completedQuests = getQuestsByStatus('completed');
  const mainQuests = getQuestsByType('main');
  const sideQuests = getQuestsByType('side');
  const dailyQuests = getQuestsByType('daily');

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="text-center space-y-2">
        <h1 className="text-3xl font-bold bg-gradient-to-r from-green-400 to-green-600 bg-clip-text text-transparent">
          任务系统
        </h1>
        <p className="text-slate-400">
          接受任务，完成挑战，获得丰厚奖励
        </p>
      </div>

      {/* 任务统计 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Card className="bg-slate-800/50 border-slate-700">
          <CardContent className="pt-4 text-center">
            <div className="text-2xl font-bold text-green-400">{availableQuests.length}</div>
            <div className="text-sm text-slate-400">可接受</div>
          </CardContent>
        </Card>
        
        <Card className="bg-slate-800/50 border-slate-700">
          <CardContent className="pt-4 text-center">
            <div className="text-2xl font-bold text-blue-400">{activeQuests.length}</div>
            <div className="text-sm text-slate-400">进行中</div>
          </CardContent>
        </Card>
        
        <Card className="bg-slate-800/50 border-slate-700">
          <CardContent className="pt-4 text-center">
            <div className="text-2xl font-bold text-amber-400">{completedQuests.length}</div>
            <div className="text-sm text-slate-400">已完成</div>
          </CardContent>
        </Card>
        
        <Card className="bg-slate-800/50 border-slate-700">
          <CardContent className="pt-4 text-center">
            <div className="text-2xl font-bold text-purple-400">{mainQuests.length}</div>
            <div className="text-sm text-slate-400">主线任务</div>
          </CardContent>
        </Card>
      </div>

      {/* 任务标签页 */}
      <Tabs value={selectedTab} onValueChange={setSelectedTab}>
        <TabsList className="grid w-full grid-cols-5 bg-slate-800 border-slate-700">
          <TabsTrigger value="available" className="data-[state=active]:bg-green-600">
            可接受
          </TabsTrigger>
          <TabsTrigger value="active" className="data-[state=active]:bg-blue-600">
            进行中
          </TabsTrigger>
          <TabsTrigger value="completed" className="data-[state=active]:bg-amber-600">
            已完成
          </TabsTrigger>
          <TabsTrigger value="main" className="data-[state=active]:bg-purple-600">
            主线
          </TabsTrigger>
          <TabsTrigger value="daily" className="data-[state=active]:bg-orange-600">
            日常
          </TabsTrigger>
        </TabsList>

        {/* 可接受任务 */}
        <TabsContent value="available" className="space-y-4">
          <Card className="bg-slate-800/50 border-slate-700">
            <CardHeader>
              <CardTitle className="text-green-400 flex items-center space-x-2">
                <Target className="h-5 w-5" />
                <span>可接受的任务</span>
              </CardTitle>
              <CardDescription className="text-slate-400">
                选择适合你当前等级的任务开始冒险
              </CardDescription>
            </CardHeader>
            <CardContent>
              {availableQuests.length > 0 ? (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {availableQuests.map((quest) => (
                    <QuestCard
                      key={quest.id}
                      quest={quest}
                      onAccept={handleAcceptQuest}
                    />
                  ))}
                </div>
              ) : (
                <div className="text-center py-8 text-slate-400">
                  <ScrollText className="h-12 w-12 mx-auto mb-4 opacity-50" />
                  <p>暂无可接受的任务</p>
                  <p className="text-sm mt-2">提升等级或境界来解锁更多任务</p>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* 进行中任务 */}
        <TabsContent value="active" className="space-y-4">
          <Card className="bg-slate-800/50 border-slate-700">
            <CardHeader>
              <CardTitle className="text-blue-400 flex items-center space-x-2">
                <Clock className="h-5 w-5" />
                <span>进行中的任务</span>
              </CardTitle>
              <CardDescription className="text-slate-400">
                完成这些任务来获得奖励
              </CardDescription>
            </CardHeader>
            <CardContent>
              {activeQuests.length > 0 ? (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {activeQuests.map((quest) => (
                    <QuestCard
                      key={quest.id}
                      quest={quest}
                      onComplete={handleCompleteQuest}
                    />
                  ))}
                </div>
              ) : (
                <div className="text-center py-8 text-slate-400">
                  <Clock className="h-12 w-12 mx-auto mb-4 opacity-50" />
                  <p>没有进行中的任务</p>
                  <p className="text-sm mt-2">去接受一些任务开始冒险吧</p>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* 已完成任务 */}
        <TabsContent value="completed" className="space-y-4">
          <Card className="bg-slate-800/50 border-slate-700">
            <CardHeader>
              <CardTitle className="text-amber-400 flex items-center space-x-2">
                <Trophy className="h-5 w-5" />
                <span>已完成的任务</span>
              </CardTitle>
              <CardDescription className="text-slate-400">
                你的冒险成就记录
              </CardDescription>
            </CardHeader>
            <CardContent>
              {completedQuests.length > 0 ? (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {completedQuests.map((quest) => (
                    <QuestCard
                      key={quest.id}
                      quest={quest}
                    />
                  ))}
                </div>
              ) : (
                <div className="text-center py-8 text-slate-400">
                  <Trophy className="h-12 w-12 mx-auto mb-4 opacity-50" />
                  <p>还没有完成任何任务</p>
                  <p className="text-sm mt-2">完成任务来建立你的成就记录</p>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* 主线任务 */}
        <TabsContent value="main" className="space-y-4">
          <Card className="bg-slate-800/50 border-slate-700">
            <CardHeader>
              <CardTitle className="text-purple-400 flex items-center space-x-2">
                <Star className="h-5 w-5" />
                <span>主线任务</span>
              </CardTitle>
              <CardDescription className="text-slate-400">
                推进主要剧情的重要任务
              </CardDescription>
            </CardHeader>
            <CardContent>
              {mainQuests.length > 0 ? (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {mainQuests.map((quest) => (
                    <QuestCard
                      key={quest.id}
                      quest={quest}
                      onComplete={handleCompleteQuest}
                    />
                  ))}
                </div>
              ) : (
                <div className="text-center py-8 text-slate-400">
                  <Star className="h-12 w-12 mx-auto mb-4 opacity-50" />
                  <p>没有主线任务</p>
                  <p className="text-sm mt-2">去可接受任务中寻找主线任务</p>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* 日常任务 */}
        <TabsContent value="daily" className="space-y-4">
          <Card className="bg-slate-800/50 border-slate-700">
            <CardHeader>
              <CardTitle className="text-orange-400 flex items-center space-x-2">
                <Clock className="h-5 w-5" />
                <span>日常任务</span>
              </CardTitle>
              <CardDescription className="text-slate-400">
                每日可重复的任务，获得稳定收益
              </CardDescription>
            </CardHeader>
            <CardContent>
              {dailyQuests.length > 0 ? (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {dailyQuests.map((quest) => (
                    <QuestCard
                      key={quest.id}
                      quest={quest}
                      onComplete={handleCompleteQuest}
                    />
                  ))}
                </div>
              ) : (
                <div className="text-center py-8 text-slate-400">
                  <Clock className="h-12 w-12 mx-auto mb-4 opacity-50" />
                  <p>没有日常任务</p>
                  <p className="text-sm mt-2">去可接受任务中寻找日常任务</p>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}